<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, getCurrentInstance, onMounted, reactive, nextTick } from 'vue'
import api from '@/api'; // 统一导入 API

const tableData = ref([])
const { proxy } = getCurrentInstance()
const getEmployeeData = async () => {
    try {
        let data = await api.employee.getEmployeeData(config);

        // 辅助函数：计算年龄
        const calculateAge = (birthDateString) => {
            const birthDate = new Date(birthDateString);
            const today = new Date();
            let age = today.getFullYear() - birthDate.getFullYear();
            const monthDifference = today.getMonth() - birthDate.getMonth();
            const dayDifference = today.getDate() - birthDate.getDate();

            if (monthDifference < 0 || (monthDifference === 0 && dayDifference < 0)) {
                age--;
            }
            return age;
        };

        // 对职位和年龄字段进行处理
        tableData.value = data.records.map(item => ({
            ...item,
            position: item.position === 1 ? '店长' : '店员',
            // sex: item.sex === 1 ? '男' : '女', // 假设 sex 是一个数字，1 代表男性
            age: calculateAge(item.birthDate), // 添加年龄字段并计算值
        }));

        config.total = data.total; // 给分页的总记录数赋值（注意这里应该是 data.total 而不是 data.count，具体取决于你的 API 响应结构）
    } catch (error) {
        console.error('Failed to fetch employee data:', error);
        // 可以使用 ElMessage 或其他方式显示错误消息
        ElMessage.error('获取员工数据失败，请稍后再试');
    }
};
const tableLabel = reactive([
    {
        prop: 'name',
        label: '姓名'
    },
    {
        prop: 'age',
        label: '年龄'
    },
    {
        prop: 'sex',
        label: '性别'
    },
    {
        prop: 'position',
        label: '职位'
    },
    {
        prop: 'phone',
        label: '电话号码',
        width: 200
    },
    {
        prop: 'address',
        label: '地址',
        width: 300
    },
    {
        prop: 'birthDate',
        label: '出生日期',
        width: 200
    },
    {
        prop: 'idCard',
        label: '身份证号',
        width: 200
    },
    {
        prop: 'updateTime',
        label: '最近一次修改时间',
        width: 200
    },

])
const fromInline = reactive({
    keyWord: ''
})
const config = reactive({
    name: '',
    total: 0,
    page: 1
})

const handleSearch = () => {
    config.name = fromInline.keyWord
    getEmployeeData()
}

const handleChange = (page) => {
    config.page = page
    getEmployeeData()
}

const handleDelete = (val) => {
    ElMessageBox.confirm("你确定要删除吗").then(async () => {
        console.log(val)
        await api.employee.deleteEmployee({ id: val.row.id })
        ElMessage({
            showClose: true,
            message: '删除成功',
            type: 'success'
        })
        getEmployeeData()
    })
}
const action = ref('add')
const dialogVisible = ref(false)
// 新增界面年龄和职位的默认配置
const formEmployee = reactive({
    sex: '女',
    position: '店员',
    address: '贵州省遵义市'
})
//表单校验规则
const rules = reactive({
    name: [{ required: true, message: "姓名是必填项", trigger: "blur" }],
    sex: [{ required: true, message: "性别是必选项", trigger: "change" }],
    position: [{ required: true, message: "职位是必选项", trigger: "change" }],
    phone: [
        { required: true, message: "11位电话是必填项", trigger: "blur" },
        { pattern: /^1[3-9]\d{9}$/, message: "请输入有效的11位电话号码", trigger: "blur" }
    ],
    idCard: [
        { required: true, message: "身份证号是必填项", trigger: "blur" },
        { pattern: /^\d{17}[\dXx]$/, message: "请输入有效的18位身份证号", trigger: "blur" }
    ],
    birthdate: [{ required: true, message: "出生日期是必选项", trigger: "change" }], // 注意：通常出生日期校验应该有一个日期格式的校验
    address: [{ required: true, message: '地址是必填项' }]
});
const handleClose = () => {
    // 获取表单，重置表单
    dialogVisible.value = false
    proxy.$refs['employeeForm'].resetFields()
}
const handleCancel = () => {
    dialogVisible.value = false
    proxy.$refs['employeeForm'].resetFields()
}
const handleAdd = () => {
    dialogVisible.value = true
    action.value = "add"
}
const timeFormat = (time) => {
    var time = new Date(time)
    var year = time.getFullYear()
    var month = time.getMonth() + 1
    var date = time.getDate()
    function add(m) {
        return m < 10 ? "0" + m : m
    }
    return year + "-" + add(month) + "-" + add(date)
}
const onSubmit = () => {
    proxy.$refs['employeeForm'].validate(async (valid) => {
        if (valid) {
            let res = null;
            formEmployee.birthDate = /^\d{4}-\d{2}-\d{2}$/.test(formEmployee.birthDate) ? formEmployee.birthDate : timeFormat(formEmployee.birthDate)
            if (action.value === 'add') {
                // console.log(formEmployee)
                res = await api.employee.addEmployee(formEmployee)
            } else {
                res = await api.employee.editEmployee(formEmployee)
            }
            if (res) {
                dialogVisible.value = false;  // 关闭（新增/修改）页面

                let messageType;  // 定义一个变量来存储消息类型
                if (res.includes('成功')) {
                    messageType = 'success';  // 如果res包含“成功”，则类型为success
                } else {
                    messageType = 'error';  // 否则，类型为error
                }

                ElMessage({
                    showClose: true,
                    message: res,
                    type: messageType
                });

                await proxy.$refs['employeeForm'].resetFields();  // 重置表单字段
                getEmployeeData();  // 获取员工数据
            }
        } else {
            ElMessage({
                showClose: true,
                message: '请输入正确的内容',
                type: 'error'
            })
        }
    })

}
// 编辑员工
const handleEdit = (val) => {
    action.value = 'edit'
    dialogVisible.value = true
    nextTick(() => {
        // 用于在下次DOM更新循环结束之后执行延迟回调
        Object.assign(formEmployee, {
            ...val,
            // sex:''+val.sex,
            // position: ''+ val.position
        })
    })
    console.log(val)
}
onMounted(() => {
    getEmployeeData()
})
</script>

<template>
    <div class="Employee-header">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-form :inline="true" :model="fromInline">
            <el-form-item label="姓名">
                <el-input placeholder="请输入员工姓名" v-model="fromInline.keyWord" @input="handleSearch"/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div class="table">
        <div v-if="tableData.length === 0">
            <el-empty description="没有数据" />
        </div>
        <div v-else>
            <el-table :data="tableData" style="width: 100%">
                <el-table-column v-for="item in tableLabel" :key='item.prop' :width="item.width ? item.width : 125"
                    :prop="item.prop" :label="item.label" />
                <!-- 按钮 -->
                <el-table-column fixed="right" label="操作" min-width="120">
                    <template #="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                            编辑
                        </el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope, row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination background layout="prev, pager, next" size="small" :total="config.total"
                @current-change="handleChange" />
        </div>
    </div>

    <!-- 用户新界面 -->
    <el-dialog v-model="dialogVisible" :title="action == 'add' ? '新增员工' : '编辑员工'" width="35%"
        :before-close="handleClose">
        <!--需要注意的是设置了:inline="true"，
		会对el-select的样式造成影响，我们通过给他设置一个class=select-clean
		在css进行处理-->
        <el-form :inline="true" :model="formEmployee" :rules="rules" ref="employeeForm">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="formEmployee.name" placeholder="请输入姓名" />
                    </el-form-item>
                </el-col>
                <el-col :span="12"> <!-- 这里我使用了24来占据整行，但你可以根据需要调整 -->
                    <el-form-item label="身份证" prop="idCard">
                        <el-input v-model="formEmployee.idCard" placeholder="请输入身份证" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item class="select-clean" label="性别" prop="sex">
                        <el-select v-model="formEmployee.sex" placeholder="请选择">
                            <el-option label="男" value="男" />
                            <el-option label="女" value="女" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item class="select-clean" label="职位" prop="position">
                        <el-select v-model="formEmployee.position" placeholder="请选择">
                            <el-option label="店长" value="店长" />
                            <el-option label="店员" value="店员" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="电话" prop="phone">
                        <el-input v-model="formEmployee.phone" placeholder="请输入电话" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="出生日期" prop="birthDate">
                        <el-date-picker v-model="formEmployee.birthDate" type="date" placeholder="请输入"
                            style="width: 100%" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="地址" prop="address">
                        <el-input v-model="formEmployee.address" placeholder="请输入地址" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row style="justify-content: flex-end">
                <el-form-item>
                    <el-button type="primary" @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="onSubmit">确定</el-button>
                </el-form-item>
            </el-row>
        </el-form>
    </el-dialog>
</template>

<style scoped lang="less">
.Employee-header {
    display: flex;
    justify-content: space-between;
}

.table {
    position: relative;
    height: 520px;

    .pager {
        position: absolute;
        right: 10px;
        bottom: 30px;
    }

    .el-table {
        width: 100%;
        height: 500px;
    }
}

.select-clean {
    display: flex;
}
</style>